<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Admin as AdminModel;

class Admin extends Controller
{
    //管理员列表
    public function admin_list()
    {
        $admins   = AdminModel::orderBy('is_super', 'asc')->orderBy('status')->paginate(10);
        $viewData = [
            'admins' => $admins
        ];
        return view('admin.admin.list', $viewData);
    }

    //状态操作
    public function status()
    {
        $data      = request()->only(['id', 'status']);
        $adminInfo = AdminModel::find($data['id']);
//        TODO Mysql数据库的BUG
        $adminInfo->status = request('status') ? '0' : '1';
        $result            = $adminInfo->save();
        if ($result) {
            $msg = [
                'code' => 1,
                'msg'  => '操作成功',
                'url'  => url('admin/admin_list')
            ];
        } else {
            $msg = [
                'code' => 0,
                'msg'  => '操作失败'
            ];
        }
        return $msg;
    }

    public function add()
    {
        if (request()->isMethod('post')) {
            $data   = request()->only(['username', 'password', 'nickname', 'email']);
            $result = (new AdminModel)->add($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg'  => '添加成功',
                    'url'  => url('admin/admin_list')
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg'  => $result,
                ];
            }
            return $msg;
        };
        return view('admin.admin.add');
    }

    //编辑
    public function edit()
    {
        if (request()->isMethod('post')) {
            $data   = request()->only(['id', 'username', 'nickname', 'password', 'email']);
            $result = (new AdminModel)->edit($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg'  => '编辑成功',
                    'url'  => url('admin/admin_list')
                ];
            } else {
                $msg = [
                    'code' => 0,
                    'msg'  => $result
                ];
            }
            return $msg;
        }
        $adminInfo = AdminModel::find(request('id'));
        $viewData  = [
            'admin' => $adminInfo
        ];
        return view('admin.admin.edit', $viewData);
    }

//    删除
    public function del()
    {
        $adminInfo = AdminModel::find(request('id'));
        $result    = $adminInfo->delete();
        if ($result) {
            $msg = [
                'url' => 1,
                'msg' => '删除成功',
                'url' => url('admin/admin_list')
            ];
        }else{
            $msg = [
                'url' => 0,
                'msg' => '删除失败',
            ];
        }
        return $msg;
    }
}
